package eerbaar.v2.client;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.net.URL;

import javax.swing.JPanel;

import eerbaar.v2.app.core.App;
import eerbaar.v2.gamebuilder.Config;

@SuppressWarnings("serial")
public class Applet extends javax.swing.JApplet implements Runnable {

    private Thread animator;
    private boolean running = true;

    public Applet() {
        //
    }

    @Override
    public void init() {
        super.init();

        final String userid = getParameter("userid");
        System.out.println("userid    =\t" + userid);
        final String client = getParameter("client");
        System.out.println("client    =\t" + client);

        Config.setCalcUserId(userid);

        URL url = getCodeBase();
        System.out.println("code base =\t" + url);
        if (url.getProtocol().startsWith("http")) {
            String host = url.getHost();
            if (url.getPort() > 0) {
                host += ":" + url.getPort();
            }
            Config.setCalcServer(host);
        }

        Main.init(super.rootPane.getContentPane());
    }

    @Override
    public void paint(Graphics g) {

        Dimension d = new Dimension(780, 610);

        Image offImage = createImage(d.width, d.height);
        Graphics offGraphics = offImage.getGraphics();

        JPanel panel = App.instance().getRightPanel().getPanel();
        offGraphics.translate(510, 0);
        panel.paint(offGraphics);
        offGraphics.translate(-510, 0);

        paintFrame(offGraphics);
        g.drawImage(offImage, 0, 0, null);
    }

    public void paintFrame(Graphics g) {
        App.instance().paint((Graphics2D) g);
    }

    @Override
    public void run() {
        while (this.running) {
            repaint();
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                break;
            }
        }
    }

    @Override
    public void start() {
        this.animator = new Thread(this);
        this.animator.start();
    }

    @Override
    public void stop() {
        this.running = false;
    }

}
